import { WebDriver, By } from 'selenium-webdriver';

// 尝试使用系统返回键
export async function systemBack(driver: WebDriver) {
  await driver.sleep(2000);
  
  // 首先检查 UiAutomator2 服务状态
  const isServiceRunning = await checkUiAutomator2Status(driver);
  if (!isServiceRunning) {
    console.log('检测到 UiAutomator2 服务崩溃，尝试重启服务...');
    try {
      await restartUiAutomator2(driver);
      await driver.sleep(5000); // 等待服务完全重启
      console.log('UiAutomator2 服务重启成功，继续执行返回操作');
    } catch (restartError) {
      console.error('重启 UiAutomator2 服务失败:', restartError);
      throw new Error('UiAutomator2 服务重启失败，无法继续操作');
    }
  }
  
  try {
    // 方法1: 使用 mobile: pressKey 命令
    await driver.executeScript('mobile: pressKey', { keycode: 4 });
    await driver.sleep(2000);
    console.log('使用 mobile: pressKey 返回成功');
    return;
  } catch (error) {
    console.log(`mobile: pressKey 失败: ${error instanceof Error ? error.message : String(error)}`);
    
    // 如果是服务崩溃，再次尝试重启
    if (error instanceof Error && error.message.includes('instrumentation process is not running')) {
      try {
        console.log('再次尝试重启 UiAutomator2 服务...');
        await restartUiAutomator2(driver);
        await driver.sleep(5000);
        
        // 重启后再次尝试返回
        await driver.executeScript('mobile: pressKey', { keycode: 4 });
        await driver.sleep(2000);
        console.log('服务重启后返回成功');
        return;
      } catch (retryError) {
        console.log('服务重启后仍然失败，尝试其他方法');
      }
    }
    
    // 方法2: 尝试点击返回按钮
    try {
      await driver.sleep(1000);
      const backButton = await driver.findElement(By.xpath('//android.widget.ImageButton[@content-desc="返回"]'));
      await backButton.click();
      await driver.sleep(2000);
      console.log('点击返回按钮成功');
      return;
    } catch (error2) {
      console.log('点击返回按钮失败');
      
      // 方法3: 使用 ADB 命令发送返回键
      try {
        await driver.executeScript('mobile: shell', {
          command: 'input',
          args: ['keyevent', '4']
        });
        await driver.sleep(2000);
        console.log('使用 ADB shell 返回成功');
        return;
      } catch (error3) {
        console.log('ADB shell 返回失败');
        
        // 最后手段: 抛出错误，让上层处理重新创建 driver
        throw new Error('所有返回方法都失败，需要重新创建 WebDriver 实例');
      }
    }
  }
}

// 检查 UiAutomator2 服务状态
export async function checkUiAutomator2Status(driver: WebDriver): Promise<boolean> {
  try {
    await driver.executeScript('mobile: deviceInfo');
    return true;
  } catch (error) {
    console.log('UiAutomator2 服务异常:', error);
    return false;
  }
}

// 重启 UiAutomator2 服务
export async function restartUiAutomator2(driver: WebDriver): Promise<void> {
  try {
    await driver.executeScript('mobile: shell', {
      command: 'am',
      args: ['force-stop', 'io.appium.uiautomator2.server']
    });
    await driver.sleep(2000);
    
    // 重新启动服务会在下次命令时自动触发
    console.log('UiAutomator2 服务重启完成');
  } catch (error) {
    console.error('重启 UiAutomator2 服务失败:', error);
    throw error;
  }
}
